<template>
  <div :id="chartId" style="width: 100%; height: 460px; padding:20px"></div>
</template>

<script>
import m20072019CollectService from "@/service/m20072019_collect";

export default {
  name: "chart1",
  components: {
    //someComponent
  },
  props: ["chartId", "chartYjryData", "chartLwData", "centerData", "lwxzList"],
  data() {
    return {
      msg: "Hello Vue.js",
      chartDiv: null,
      chartData: null,
    };
  },
  computed: {},
  watch: {},
  mounted: function () {
    this.loadData();
  },
  methods: {
    loadData() {
      this.chartDiv = echarts.init(document.getElementById(this.chartId));
      this.chartDiv.showLoading({
          text: '数据正在加载...',
          textStyle: { fontSize : 30 , color: '#444' },
          effectOption: {backgroundColor: 'rgba(0, 0, 0, 0)'}
      });
      Promise.all([
        m20072019CollectService.getM20072019CollectList({
          filter: [["type", 0, "Education and Human Resources"]],
          order: [["year", 0]],
          pageSize: 0,
        }),
        m20072019CollectService.getM20072019CollectList({
          filter: [["type", 0, "Computer & Info Scie & Enginr"]],
          order: [["year", 0]],
          pageSize: 0,
        }),
      ]).then(([data1, data2]) => {
        this.chartData1 = data1.data;
        this.chartData2 = data2.data;
        this.initData();
        this.chartDiv.hideLoading();
      });
    },
    initData() {
      const xDataArr = [];
      const dataArr = [];
      const dataArr2 = [];
      const dataArr_2 = [];
      const dataArr_22 = [];
      this.chartData1.forEach((item) => {
        xDataArr.push(item.year);
        dataArr.push(item.count_ratio);
        dataArr2.push(item.amount_ratio);
      });
      this.chartData2.forEach((item) => {
        // xDataArr.push(item.year);
        dataArr_2.push(item.count_ratio);
        dataArr_22.push(item.amount_ratio);
      });
      this.initChart(xDataArr, dataArr, dataArr2, dataArr_2, dataArr_22);
    },
    initChart(xDataArr, dataArr, dataArr2, dataArr_2, dataArr_22) {
      if (!document.getElementById(this.chartId)) return;
      this.chartDiv = echarts.init(document.getElementById(this.chartId));
      const depart = ["教育与人力资源学部", "计算机、信息科学与工程学部"];
      const option = {
        color: ["#00d06e", "#48abfe", "#3be294", "#ffdcba"],
        tooltip: {
          trigger: "axis",
          backgroundColor: 'transparent',
          formatter: (params) => {
            params = params.sort((a, b) => a.componentIndex - b.componentIndex);
            var str = "<div class='chart-tooltip'>";
            str += `${params[0].axisValue}年${params.length === 2 ? ` ${params[0].seriesName}` : ''}<br />`;
            for (var i = 0; i < params.length; i++) {
              const index = params[i].componentIndex;
              if (params.length === 4) {
                if (index === 0 || index === 1) {
                  index === 0 && (str += `<span class="high-light">项目数:</span> <br />`);
                  // str += `${params[i].seriesName}<br />`;
                  str += `${params[i].seriesName}: <span class="high-light">${
                    this[index === 0 ? "chartData1" : "chartData2"][
                      params[i].dataIndex
                    ].count
                  } 个</span> 占比: <span class="high-light">${params[i].value}%</span></br>`;
                } else if (index === 2 || index === 3) {
                  index === 2 && (str += `<span class="high-light">经费额: </span><br />`);
                  // str += `${params[i].seriesName}<br />`;
                  str += `${params[i].seriesName}: <span class="high-light">${this.initMoney(
                    this[index === 2 ? "chartData1" : "chartData2"][
                      params[i].dataIndex
                    ].amount
                  )} 美元</span> 占比: <span class="high-light">${params[i].value}%</span></br>`;
                }
              }
              if (params.length === 2) {
                if (i === 0) {
                  str += `项目数: <span class="high-light">${
                    this[index === 0 ? "chartData1" : "chartData2"][
                      params[i].dataIndex
                    ].count
                  } 个</span> 占比: <span class="high-light">${params[i].value}%</span></br>`;
                } else {
                  str += `经费额: <span class="high-light">${this.initMoney(
                    this[index === 1 ? "chartData1" : "chartData2"][
                      params[i].dataIndex
                    ].amount
                  )} 美元</span> 占比: <span class="high-light">${params[i].value}%</span></br>`;
                }
              }
            }
            str += '</div>'
            return str;
          },
        },
        legend: {
          itemWidth: 20,
          itemHeight: 6,
          bottom: "1%",
          data: depart,
        },
        grid: [
          { bottom: "55%", left: "5%", right: "4%" },
          { top: "55%", left: "5%", right: "4%" },
        ],
        axisPointer: {
          link: [{ xAxisIndex: "all" }], //link 是一个数组，其中每一项表示一个 link group，一个 group 中的坐标轴互相联动
          label: {
            backgroundColor: "#777",
          },
        },
        yAxis: [
          {
            gridIndex: 0,
            name: "项目数（占比%）",
            type: "value",
            axisLabel: {
              show: true,
              interval: "auto",
              formatter: "{value} ",
            },
            splitLine: {
              show: true,
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            show: true,
          },
          {
            gridIndex: 1,
            name: "经费额（占比%）",
            type: "value",
            axisLabel: {
              show: true,
              interval: "auto",
              formatter: "{value} ",
            },
            splitLine: {
              show: true,
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            show: true,
          },
        ],
        xAxis: [
          {
            gridIndex: 0,
            show: false,
            type: "category",
            axisLabel: {
              interval: 0,
              show: true,
              splitNumber: 15,
              textStyle: {
                fontSize: 12,
                color: "#656565",
              },
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            data: xDataArr,
          },
          {
            gridIndex: 1,
            type: "category",
            axisLabel: {
              interval: 0,
              show: true,
              splitNumber: 15,
              textStyle: {
                fontSize: 12,
                color: "#656565",
              },
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            data: xDataArr,
          },
        ],
        series: [
          {
            name: "教育与人力资源学部",
            type: "line",
            barWidth: "20px",
            data: dataArr,
            xAxisIndex: 0,
            yAxisIndex: 0,
          },
          {
            name: "计算机、信息科学与工程学部",
            type: "line",
            barWidth: "20px",
            data: dataArr_2,
            xAxisIndex: 0,
            yAxisIndex: 0,
          },
          {
            name: "教育与人力资源学部",
            type: "line",
            barWidth: "20px",
            data: dataArr2,
            xAxisIndex: 1,
            yAxisIndex: 1,
          },
          {
            name: "计算机、信息科学与工程学部",
            type: "line",
            barWidth: "20px",
            data: dataArr_22,
            xAxisIndex: 1,
            yAxisIndex: 1,
          },
        ],
      };

      this.chartDiv.setOption(option);
      window.addEventListener('resize',()=>{
        this.chartDiv.resize();
      });
    },
    initMoney(num) {
      const originnum = num;
      num = num.toString().replace(/\$|\,/g, "");
      if (isNaN(num)) {
        num = "0";
      }
      var sign = num == (num = Math.abs(num));
      num = Math.floor(num * 100 + 0.50000000001);
      var cents = num % 100;
      num = Math.floor(num / 100).toString();
      if (cents < 10) {
        cents = "0" + cents;
      }
      for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num =
          num.substring(0, num.length - (4 * i + 3)) +
          "," +
          num.substring(num.length - (4 * i + 3));
      }
      var rs = (sign ? "" : "-") + num + "." + cents;
      return rs;
    },
  },
};
</script>

<style>
.high-light {
  color: rgba(252,85,49,.8);
}
.chart-tooltip{
      background: #fff;
    border: none;
    box-shadow: 0 0 10px rgba(0,0,0,.25);
    color: #333;
    padding: 10px;
    border-radius: 5px;
}
</style>
